package net.lahuobao.finance.controller.household;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;

import net.lahuobao.export.util.ExportFileUtil;
import net.lahuobao.finance.dao.HouseHoldMapper;
import net.lahuobao.finance.entity.household.HouseholdEntity;
import net.lahuobao.finance.service.household.HouseholdServiceI;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import java.io.IOException;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;

/**   
 * @Title: Controller
 * @Description: 个体户
 * @author zhangdaihao
 * @date 2016-08-24 18:49:17
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/householdController")
public class HouseholdController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(HouseholdController.class);

	@Autowired
	private HouseholdServiceI householdService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	@Autowired
	private ExportFileUtil exportFileUtil;
	@Autowired
	private HouseHoldMapper houseHoldDao;

	/**
	 * 导出
	 * @throws IOException 
	 */
	@RequestMapping(params = "exportFile")
	public void exportFile(HttpServletResponse response,HttpServletRequest request) throws IOException{
		exportFileUtil.setFileName("个体户" , "xlsx");

		Map paramMap = new HashMap();
		String businessLicense = request.getParameter("businessLicense");
		String name = request.getParameter("name");
		paramMap.put("name", name);
		paramMap.put("businessLicense", businessLicense);

		//分页情况
		int pageCount  = 1000;
		int begin =  0;
		paramMap.put("begin", begin);
		paramMap.put("pageCount", pageCount);
		
		exportFileUtil.initExport(response);

		int begin1=exportFileUtil.exportIOStream(response, queryDataForExport(paramMap), pageCount, begin,0);

		while(begin1!=begin){
			begin = begin1;
			paramMap.put("begin", begin1);
			begin1=exportFileUtil.exportIOStream(response, queryDataForExport(paramMap), pageCount, begin1,1);
		}
		exportFileUtil.finish(response);

	}

	/***
	 * 分页查询
	 */
	private List queryDataForExport(Map map){
		List<net.lahuobao.export.datasoruce.entity.HouseholdEntity> dataList = houseHoldDao.selectHouseHoldForExport(map);
		return dataList;
	}
	/**
	 * 个体户列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("net/lahuobao/finance/household/householdList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(HouseholdEntity household,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(HouseholdEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, household, request.getParameterMap());
		
		cq.eq("isvalid", "1");
		cq.add();
		
		cq.addOrder("operateTime", SortDirection.desc);
		
		this.householdService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除个体户
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(HouseholdEntity household, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		household = systemService.getEntity(HouseholdEntity.class, household.getId());
		message = "个体户删除成功";
		household.setIsvalid("0");
		householdService.updateEntitie(household);
	//	householdService.delete(household);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加个体户
	 * 
	 * @param ids
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(HouseholdEntity household, HttpServletRequest request) throws Exception {
		String message = null;
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(household.getId())) {
			message = "个体户更新成功";
			HouseholdEntity t = householdService.get(HouseholdEntity.class, household.getId());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(household, t);
				householdService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
				message = "个体户更新失败";
			}
		} else {
			message = "个体户添加成功";
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			household.setOperateTime(df.parse(df.format(new Date())));
			household.setOperateUser(ResourceUtil.getSessionUserName().getId());
			household.setIsvalid("1");//默认有效
			if(null==household.getName()){
				message="个体户添加失败";
			}else{
				householdService.saveHousehold(household);
			}
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 个体户列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(HouseholdEntity household, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(household.getId())) {
			household = householdService.getEntity(HouseholdEntity.class, household.getId());
			req.setAttribute("householdPage", household);
		}
		return new ModelAndView("net/lahuobao/finance/household/household");
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<HouseholdEntity> list() {
		List<HouseholdEntity> listHouseholds=householdService.getList(HouseholdEntity.class);
		return listHouseholds;
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> get(@PathVariable("id") String id) {
		HouseholdEntity task = householdService.get(HouseholdEntity.class, id);
		if (task == null) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(task, HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<?> create(@RequestBody HouseholdEntity household, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<HouseholdEntity>> failures = validator.validate(household);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		householdService.save(household);

		//按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
		String id = household.getId();
		URI uri = uriBuilder.path("/rest/householdController/" + id).build().toUri();
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(uri);

		return new ResponseEntity(headers, HttpStatus.CREATED);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<?> update(@RequestBody HouseholdEntity household) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<HouseholdEntity>> failures = validator.validate(household);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		householdService.saveOrUpdate(household);

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return new ResponseEntity(HttpStatus.NO_CONTENT);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void delete(@PathVariable("id") String id) {
		householdService.deleteEntityById(HouseholdEntity.class, id);
	}
}
